﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.Collections;

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Threading;

namespace INSAForManagers
{
    public partial class FormSUM : Form
    {
        private DataTable tbl = null;
        private ArrayList colNames = new ArrayList();
        private FormMain parent;

        public FormSUM(FormMain parent)
        {
            InitializeComponent();
            this.parent = parent;
            tbl = new DataTable(); 
        }

        private void FormSUM_Load(object sender, EventArgs e)
        {
            try
            {
                addGridViewColumns();

                tbl.Rows.Clear();


                ArrayList list = DBUtil.getMTargetList((byte)parent.tscTargetType.SelectedIndex);

                //SMULTITABLE 에서 STD_POINT(평균)을 가져와서 요쇼별로 할당
                int nRow = 0;
                foreach (Hashtable tmp in list)
                {
                    DataRow row = tbl.NewRow();

                    row[0] = nRow + 1;
                    row[1] = DBUtil.getOrganName(Config.Mvi.Organ);
                    row[2] = tmp["TARGET_PCODE"];
                    row[3] = tmp["TARGET_NAME"];

                    ArrayList items = DBUtil.getItemsFromMMultitable((string)tmp["TARGET_PCODE"]);

                    if (items.Count == 0) continue;

                    double item1 = (double)items[0];
                    double item2 = (double)items[1];
                    double item3 = (double)items[2];
                    double item4 = (double)items[3];
                    double item5 = (double)items[4];
                    double total_point = Double.Parse(DBUtil.getItemFromTMultitable((string)tmp["TARGET_PCODE"], "1").ToString());
                    double std_point = Double.Parse(DBUtil.getItemFromTMultitable((string)tmp["TARGET_PCODE"], "2").ToString());

                    row[4] = item1;
                    row[5] = item2;
                    row[6] = item3;
                    row[7] = item4;
                    row[8] = item5;
                    row[9] = total_point;
                    row[10] = std_point;

                    tbl.Rows.Add(row);

                    nRow++;
                }                

                grdSumTable.Refresh();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
        }


        /// <summary>
        /// DataGridView 컬럼 정의 및 서식 적용
        /// </summary>
        private void addGridViewColumns()
        {
            DataColumn col;

            int valuer_num = Config.ValuerList.Count;

            //연번
            col = new DataColumn();
            col.DataType = Type.GetType("System.Int32");
            col.ColumnName = "연번";
            colNames.Add("연번");
            col.AllowDBNull = false;
            col.ReadOnly = true;            
            tbl.Columns.Add(col);

            //소속
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "소속";
            colNames.Add("소속");
            col.AllowDBNull = false;
            col.ReadOnly = true;            
            tbl.Columns.Add(col);

            //개인번호
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "개인번호";
            colNames.Add("개인번호");
            col.AllowDBNull = false;
            col.ReadOnly = true;            
            tbl.Columns.Add(col);

            //평가자 대상자 성명
            col = new DataColumn();
            col.DataType = Type.GetType("System.String");
            col.ColumnName = "평가대상자";
            colNames.Add("평가대상자");
            col.AllowDBNull = false;
            col.ReadOnly = true;
            tbl.Columns.Add(col);

            //교육자로서의 품성
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "교육자로서의 품성(10)";
            colNames.Add("교육자로서의 품성(10)");
            col.AllowDBNull = false;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //공직자로서의 자세
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "공직자로서의 자세(10)";
            colNames.Add("공직자로서의 자세(10)");
            col.AllowDBNull = false;            
            col.ReadOnly = false;            
            tbl.Columns.Add(col);

            //학습지도
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "학습지도(40)";
            colNames.Add("학습지도(40)");
            col.AllowDBNull = false;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //생활지도
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "생활지도(20)";
            colNames.Add("생활지도(20)");
            col.AllowDBNull = false;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //교육연구 및 담당업무
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "교육연구 및 담당업무(20)";
            colNames.Add("교육연구 및 담당업무(20)");
            col.AllowDBNull = false;
            col.ReadOnly = false;
            tbl.Columns.Add(col);


            //평가점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "평가점(100)";
            colNames.Add("평가점(100)");
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            //환산점
            col = new DataColumn();
            col.DataType = Type.GetType("System.Double");
            col.ColumnName = "환산점(30)";
            colNames.Add("환산점(30)");
            col.AllowDBNull = true;
            col.ReadOnly = false;
            tbl.Columns.Add(col);

            grdSumTable.DataSource = tbl;

            grdSumTable.Columns[0].Width = 50;
            grdSumTable.Columns[1].Width = 120;
            grdSumTable.Columns[3].Width = 60;
            grdSumTable.Columns[4].Width = 60;
            grdSumTable.Columns[5].Width = 60;
            grdSumTable.Columns[6].Width = 60;
            grdSumTable.Columns[7].Width = 60;
            grdSumTable.Columns[8].Width = 60;
            grdSumTable.Columns[9].Width = 60;
            grdSumTable.Columns[10].Width = 60;
            grdSumTable.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdSumTable.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdSumTable.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdSumTable.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdSumTable.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdSumTable.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdSumTable.Columns[7].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdSumTable.Columns[8].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdSumTable.Columns[9].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdSumTable.Columns[10].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            grdSumTable.Columns[3].Frozen = true;
            grdSumTable.Columns[2].Visible = false;
            grdSumTable.Columns[4].DefaultCellStyle.Format = "#0.000";
            grdSumTable.Columns[5].DefaultCellStyle.Format = "#0.000";
            grdSumTable.Columns[6].DefaultCellStyle.Format = "#0.000";
            grdSumTable.Columns[7].DefaultCellStyle.Format = "#0.000";
            grdSumTable.Columns[8].DefaultCellStyle.Format = "#0.000";
            grdSumTable.Columns[9].DefaultCellStyle.Format = "#0.000";
            grdSumTable.Columns[10].DefaultCellStyle.Format = "#0.000";
            grdSumTable.Columns[10].DefaultCellStyle.BackColor = Color.LightGray;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
            parent.stateRefresh();
            FormMain.setMnuSumEnabled();
        }

        private void btnSum_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < DBUtil.getMTargetCount(getTargetType()); i++)
            {
                DataRow row = tbl.Rows[i];
                double item1 = Double.Parse(row[4].ToString());
                double item2 = Double.Parse(row[5].ToString());
                double item3 = Double.Parse(row[6].ToString());
                double item4 = Double.Parse(row[7].ToString());
                double item5 = Double.Parse(row[8].ToString());

                double total_point = item1 + item2 + item3 + item4 + item5;
                if (total_point == 0.0)
                {
                    MessageBox.Show("다면평가 요소별 평균을 먼저 계산하세요.    ", "확인");
                    return;
                }

                double std_point = total_point * 0.3;

                row[9] = total_point;
                row[10] = std_point;
            }


        }

        private byte getTargetType()
        {
            return (byte)parent.tscTargetType.SelectedIndex;
        }        
       
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                ArrayList list = new ArrayList();
                for (int i = 0; i < DBUtil.getMTargetCount(getTargetType()); i++)
                {

                    if (Double.Parse(grdSumTable.Rows[i].Cells[9].Value.ToString()) < 1.0 || Double.Parse(grdSumTable.Rows[i].Cells[9].Value.ToString()) < 1.0)
                    {
                        MessageBox.Show("합산 버튼을 클릭하여 평가점과 환산점을 계산한 후 저장하세요!    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    ArrayList data = new ArrayList();
                    data.Add(grdSumTable.Rows[i].Cells[2].Value);
                    data.Add(grdSumTable.Rows[i].Cells[9].Value);
                    data.Add(grdSumTable.Rows[i].Cells[10].Value);

                    list.Add(data);

                }

                DBUtil.writeSumInfo(list);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show("저장하였습니다.    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnXls_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(printXls));
            t.Start();
        }

        /// <summary>
        /// 엑셀 내보내기
        /// </summary>
        private void printXls()
        {
            try
            {
                //엑셀 열기
                Util.openXls(Application.StartupPath + "\\MultiSum");

                //레인지 객체 선언
                Excel.Range range;

                // 평가기간 설정

                //시작
                range = Util.OSheet.get_Range("A3",Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.SDate);

                //종료
                range = Util.OSheet.get_Range("A4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.EDate);

                //평정자 성명
                range = Util.OSheet.get_Range("E4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Confirmer);

                //확인자 성명
                range = Util.OSheet.get_Range("I4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Evaluer1 + (Config.Mvi.Evaluer2.Equals("")?"":"," + Config.Mvi.Evaluer2));

                //소속
                string organ_name = DBUtil.getOrganName(Config.Mvi.Organ);

                //평가자
                string valuer = "다면평가자";                

                //레코드
                ArrayList list = DBUtil.getMTargetListFromTMULTITABLE((byte)parent.tscTargetType.SelectedIndex);
                if (list.Count == 0)
                {
                    MessageBox.Show("합산 후 저장하신 다음 인쇄하세요!    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                object[,] arr = new object[list.Count,10];
                for (int i = 0; i < list.Count; i++)
                {
                    //소속
                    arr[i, 0] = organ_name;
                    arr[i, 1] = DBUtil.getMTargetName(list[i].ToString());
                    arr[i, 2] = valuer;
                    arr[i, 3] = DBUtil.getElementInfo(list[i].ToString(), "1")[1];
                    arr[i, 4] = DBUtil.getElementInfo(list[i].ToString(), "2")[1];
                    arr[i, 5] = DBUtil.getElementInfo(list[i].ToString(), "3")[1];
                    arr[i, 6] = DBUtil.getElementInfo(list[i].ToString(), "4")[1];
                    arr[i, 7] = DBUtil.getElementInfo(list[i].ToString(), "5")[1];
                    arr[i, 8] = DBUtil.getItemFromTMultitable(list[i].ToString(), "1");
                    arr[i, 9] = DBUtil.getItemFromTMultitable(list[i].ToString(), "2");
                }

                range = Util.OSheet.get_Range("A16", "J" + (15 + list.Count).ToString());
                range.set_Value(Missing.Value, arr);

                range = Util.OSheet.get_Range("A16", "k" + (15 + list.Count).ToString());
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;

                PrintDialog dlg = new PrintDialog();
                dlg.AllowSomePages = true;
                dlg.AllowCurrentPage = true;
                dlg.AllowPrintToFile = false;
                dlg.PrinterSettings.Duplex = System.Drawing.Printing.Duplex.Vertical;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    int startPage = dlg.PrinterSettings.FromPage;
                    int endPage = dlg.PrinterSettings.ToPage;

                    if (startPage > 0 && endPage > 0)
                    {
                        Util.OSheet.get_Range("A16", "k" + (15 + list.Count).ToString()).PrintOut(startPage, endPage, dlg.PrinterSettings.Copies, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value);                
                    }
                    else
                    {
                        Util.OSheet.get_Range("A16", "k" + (15 + list.Count).ToString()).PrintOut(Missing.Value, Missing.Value, dlg.PrinterSettings.Copies, false, Missing.Value, Missing.Value, Missing.Value, Missing.Value);                        
                    }

                }
                dlg.Dispose();

                Util.closeXls();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Util.closeXls();
            }
        }
    }
}
